package com.outsourcing.bottle.ui;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ext.SatelliteMenu;
import android.view.ext.SatelliteMenu.SateliteClickedListener;
import android.view.ext.SatelliteMenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.adapter.GridLikeAdapter;
import com.outsourcing.bottle.db.BottleTypeTable;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.domain.BottleEntry;
import com.outsourcing.bottle.domain.BottleFeedEntry;
import com.outsourcing.bottle.domain.BottleInfo;
import com.outsourcing.bottle.domain.BottleLikeEntry;
import com.outsourcing.bottle.domain.BottleTimelineInfo;
import com.outsourcing.bottle.domain.BottleTypeEntry;
import com.outsourcing.bottle.domain.LocationEntry;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ImageLoader;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.widget.CustomGridView;
import com.outsourcing.bottle.widget.CustomPopupWindow;
import com.outsourcing.bottle.widget.ElasticScrollView;
import com.outsourcing.bottle.widget.TryRefreshableView;

public class BottleSingleActivity extends BasicActivity implements
		BasicUIEvent, OnClickListener, Callback {
	
	private static final int EXEU_REFRESH_CONTENT = 7;
	private static final int EXEU_GET_BOTTLE_PRIV_OPERATION = 8;
	private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS = 9;
	private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE = 10;
	private static final int EXEU_SEND_BOTTLE_PRIV_FAILED = 11;
	private static final int EXEU_LIKE_OPERATION = 12;
	private static final int EXEU_UNLIKE_OPERATION = 13;
	private static final int EXEU_LIKE_OPERATION_FAILED = 14;
	private static final int EXEU_GET_DATA_NOTHING = 17;
	private static final int EXEU_GET_TIMELINE = 18;
	private static final int EXEU_GET_TIMELINE_FAILED = 19;
	private static final int EXEU_OPEN_BOTTLE_OPERATION = 20;
	private static final int EXEU_OPEN_BOTTLE_SUCCESS = 21;
	private static final int EXEU_OPEN_BOTTLE_FAILED = 22;
	private static final int EXEU_GET_DATA_FAILED = 23;
	private static final int EXEU_DROP_BOTTLE_SUCCESS =24;
	private static final int EXEU_DROP_BOTTLE_FAILED = 25;
	private static final int EXEU_DROP_BOTTLE_OPERATION = 26;
	private final int throw_bottle_init_location = 27;
	private static final int EXEU_SET_BTPIC_PAINT = 28;
	View mContentView = null;
	ElasticScrollView elasticScrollView = null;
	private ImageLoader imageLoader = null;
	private TryRefreshableView rv;
	private LinearLayout ll_content;
	private ScrollView sv;
	private Handler handler;
	private ImageView iv_back;
	private int btId;
	private BottleTimelineInfo bottlelist;
	private List<BottleEntry> mBottleList;
	private int page = 1;
	private ImageView iv_menu;
	private CustomPopupWindow mLikePopview;
	private BottleTypeEntry entry;
	private int btTypeId;
	private boolean isRefresh;

	private final int menu_uploadphoto = 105;
	private final int menu_exprofile = 104;
	private final int menu_exphoto = 103;
	private final int menu_gainbt = 102;
	private final int menu_sendbt = 101;
	private final int user_baseinfo_notfull = 100;
//	private ImageView messageView;
	
	private ImageLoader btConfigLoader;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bottle_single);

		btId = getIntent().getIntExtra("btid", 0);
		handler = new Handler(this);
		imageLoader = new ImageLoader(this, AppContext.BottleTimelineIcon);
		btConfigLoader = new ImageLoader(this, AppContext.BOTTLE_CONFIG);

		initLayout();
		initLikePopup();
		initSateMenu();
		UICore.eventTask(this, BottleSingleActivity.this, EXEU_GET_TIMELINE, "", null);

	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case EXEU_GET_TIMELINE:
			getTimeLine(4, btId);
			break;
		case EXEU_REFRESH_CONTENT:
			isRefresh = true;
			getTimeLine(4, btId);
			break;
		case EXEU_GET_BOTTLE_PRIV_OPERATION:
			getSendSingleBtPriv(btTypeId, btId);
			break;
		case EXEU_LIKE_OPERATION:
			likeOperation(btId, 1);
			break;
		case EXEU_UNLIKE_OPERATION:
			likeOperation(btId, 2);
			break;
		case EXEU_OPEN_BOTTLE_OPERATION:
			openBottle(btId);
			break;
		case EXEU_DROP_BOTTLE_OPERATION:
			dropBottle(btId);
			break;
		case throw_bottle_init_location:
			Object idObj = obj;
			networkLocat();
			Message msg = Message.obtain(handler, throw_bottle_init_location, idObj);
			handler.sendMessage(msg);
			break;
		case EXEU_SET_BTPIC_PAINT:
			int optype = (Integer)obj;
			setBtpicPaint(btId, optype);
			break;
		default:
			break;
		}
	}
	/**
	 * 设置瓶子照片涂鸦权限接口
	 * @param btid 瓶子ID
	 * @param optype 设置是否允许涂鸦。选择项：不允许（0）、允许（1）
	 */
	private void setBtpicPaint(int btid,int optype) {
		this.btId = btid;
		StringBuffer url = new StringBuffer(UrlConfig.set_btpic_paint);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btid);
		url.append("&optype=" + optype);
		ServiceUtils.dout("setBtpicPaint url:" + url.toString());
		try {
			String result = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("setBtpicPaint result:" + result);
			if (result != null) {
				JSONObject object = new JSONObject(result);
				JSONObject resultObj = object.getJSONObject("results");
				int authok = resultObj.getInt("success");
				if (authok == 0) {
					String errmsg = resultObj.getString("errmsg");
					Message msg = Message.obtain(handler, EXEU_GET_TIMELINE_FAILED, errmsg);
					handler.sendMessage(msg);
				} else {
					String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, EXEU_SET_BTPIC_PAINT, successmsg);
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void initSateMenu() {
		SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu);
		menu.setVisibility(View.VISIBLE);
		List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>();
		items.add(new SatelliteMenuItem(menu_exprofile,
				R.drawable.menu_exprofile));
		items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto));
		items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt));
		items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt));
		items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto));
		
		menu.addItems(items);
		menu.setOnItemClickedListener(new SateliteClickedListener() {

			public void eventOccured(int id) {
				switch (id) {
				case menu_sendbt: // 扔瓶子
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent throwIntent = new Intent(
										BottleSingleActivity.this,
										ChooseBottleActivity.class);
								throwIntent.putExtra("type", "throw");
								startActivity(throwIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_gainbt: // 捞瓶子
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent tryIntent = new Intent(
										BottleSingleActivity.this,
										ChooseBottleActivity.class);
								tryIntent.putExtra("type", "try");
								startActivity(tryIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_exphoto: // 交换照片
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent exchangeInfoIntent = new Intent(
										BottleSingleActivity.this,
										ChooseFriendActivity.class);
								exchangeInfoIntent
										.putExtra(
												"choose_friend_type",
												AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE);
								startActivity(exchangeInfoIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_exprofile: // 交换资料
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								LoginUserInfoTable userTable = new LoginUserInfoTable();
								LoginUserInfoEntry userEntry = userTable
										.getLoginUserInfo(AppContext
												.getInstance().getLogin_uid());
								if (userEntry.getBasicinfo_fullfill() == 0) {
									handler.sendEmptyMessage(user_baseinfo_notfull);
								} else {
									Intent exchangeFileIntent = new Intent(
											BottleSingleActivity.this,
											ChooseFriendActivity.class);
									exchangeFileIntent
											.putExtra(
													"choose_friend_type",
													AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE);
									startActivity(exchangeFileIntent);
								}
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_uploadphoto:
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent intent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class);
								Bundle extras = new Bundle();
								extras.putString("from_type", AppContext.UPLOAD_PHOTO);
								extras.putInt("albumid", 0);
								extras.putInt("ouid", AppContext.getInstance().getLogin_uid());
								intent.putExtras(extras);
								startActivity(intent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				default:
					break;
				}
			}
		});
	}
	
	private void dropBottle(int btId) {
		StringBuffer url = new StringBuffer(UrlConfig.discard_bt);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		ServiceUtils.dout("dropBottle url:" + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("dropBottle result:" + results);
			if (null != results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int success = resultObj.getInt("success");
				String errmsg = resultObj.getString("errmsg");
				String successmsg = resultObj.getString("successmsg");
				if (success == 1) {
					Message message = handler.obtainMessage(
							EXEU_DROP_BOTTLE_SUCCESS, successmsg);
					handler.sendMessage(message);

				} else {
					Message message = handler.obtainMessage(
							EXEU_DROP_BOTTLE_FAILED, errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void openBottle(int btId) {
		StringBuffer url = new StringBuffer(UrlConfig.open_bt);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		ServiceUtils.dout("openBottle url:" + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("openBottle result:" + results);
			if (null != results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int success = resultObj.getInt("success");
				String errmsg = resultObj.getString("errmsg");
				String successmsg = resultObj.getString("successmsg");
				if (success == 1) {

					StringBuffer mSingleBottleUrl = new StringBuffer(
							UrlConfig.get_bt_timeline);
					mSingleBottleUrl.append("?clitype=2");
					mSingleBottleUrl.append("&language=" + AppContext.language);
					mSingleBottleUrl.append("&login_uid="
							+ AppContext.getInstance().getLogin_uid());
					mSingleBottleUrl.append("&login_token="
							+ AppContext.getInstance().getLogin_token());
					mSingleBottleUrl.append("&mode=4&btid=" + btId);
					ServiceUtils.dout("get open bottle url:"
							+ mSingleBottleUrl.toString());
					String singleResult = HttpUtils.doGet(mSingleBottleUrl
							.toString());
					ServiceUtils.dout("get open bottle results :"
							+ singleResult.toString());

					Gson gson = new Gson();
					BottleTimelineInfo singleBottleInfo = gson.fromJson(
							singleResult, BottleTimelineInfo.class);
					mBottleList = singleBottleInfo.getBts_list();

					Message message = handler.obtainMessage(
							EXEU_OPEN_BOTTLE_SUCCESS, successmsg);
					handler.sendMessage(message);
				} else {
					Message message = handler.obtainMessage(
							EXEU_OPEN_BOTTLE_FAILED, errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Message message = handler.obtainMessage(
					EXEU_GET_DATA_FAILED);
			handler.sendMessage(message);
		}
	}

	private void getTimeLine(int mode, int btId) {
		if (AppContext.getInstance().getLogin_uid() == 0
				|| AppContext.getInstance().getLogin_token() == null) {
			initConfig();
		}
		StringBuffer url = new StringBuffer(UrlConfig.get_bt_timeline);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&mode=" + mode);
		url.append("&btid=" + btId);
		url.append("&count=10");
		url.append("&page=" + page);
		url.append("&likescount=10");
		url.append("&feedscount=5");
		ServiceUtils.dout("timeline url:" + url.toString());

		try {
			String result = HttpUtils.doGet(url.toString());

			if (result == null) {
				return;
			}
			System.out.println("result:" + result);
			Gson gson = new Gson();
			bottlelist = gson.fromJson(result, BottleTimelineInfo.class);
			if (bottlelist.getResults().getAuthok() == 1) {
				mBottleList = bottlelist.getBts_list();
				Message message = Message.obtain(handler);
				message.what = EXEU_GET_TIMELINE;
				handler.sendMessage(message);
			} else {
				Message message = handler.obtainMessage(
						EXEU_GET_TIMELINE_FAILED, bottlelist.getResults()
								.getErrmsg());
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** 获取扔瓶子的权限 */
	public void getSendSingleBtPriv(int btTypeId, int btId) {
		StringBuffer url = new StringBuffer(UrlConfig.get_sendsinglebt_priv);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&bttypeid=" + btTypeId);
		ServiceUtils.dout("sendsingleBT private url:" + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("getsendsinglebt_priv result:" + results);
			if (null != results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int authok = resultObj.getInt("authok");
				String errmsg = resultObj.getString("errmsg");

				if (authok == 1) {
					JSONObject privObj = obj.getJSONObject("sendsinglebt_priv");
					int enable = privObj.getInt("enable");
					String reason = privObj.getString("reason");

					if (enable == 1) {
						Bundle bundle = new Bundle();
						bundle.putInt("type", btTypeId);
						bundle.putInt("btid", btId);
						bundle.putString("reason", reason);
						Message message = handler
								.obtainMessage(EXEU_SEND_BOTTLE_PRIV_SUCCESS);
						message.setData(bundle);
						handler.sendMessage(message);
					} else {
						Message message = handler.obtainMessage(
								EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE,
								reason);
						handler.sendMessage(message);
					}

				} else {
					Message message = handler.obtainMessage(
							EXEU_SEND_BOTTLE_PRIV_FAILED, errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initLayout() {
		iv_back = (ImageView) findViewById(R.id.topbar_back);
		iv_back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		iv_menu = (ImageView) findViewById(R.id.topbar_menu);
		iv_menu.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(BottleSingleActivity.this, HomeActivity.class);
				intent.putExtra("currentItem", 1);
				startActivity(intent);
				finish();	
			}
		});


//		messageView = (ImageView) findViewById(R.id.notice_message_count);
//		messageView.setOnClickListener(this);
		
		sv = (ScrollView) findViewById(R.id.trymySv);
		rv = (TryRefreshableView) findViewById(R.id.trymyRV);
		rv.mfooterView = (View) findViewById(R.id.tryrefresh_footer);
		rv.sv = sv;
		ll_content = (LinearLayout) findViewById(R.id.ll_content);
		// 隐藏mfooterView
		rv.mfooterViewText = (TextView) findViewById(R.id.tryrefresh_footer_text);
		rv.mfooterViewText.setVisibility(View.GONE);
		// 监听是否加载刷新
		rv.setRefreshListener(new TryRefreshableView.RefreshListener() {

			@Override
			public void onRefresh() {
				if (rv.mRefreshState == 4) {
					page = 1;
					UICore.eventTask(BottleSingleActivity.this,
							BottleSingleActivity.this, EXEU_REFRESH_CONTENT,
							null, null);
				}
				if (rv.mfooterRefreshState == 4) {
					rv.finishRefresh();
				}

			}
		});

	}

	private void setViewVlaue(final BottleEntry message) {
		ll_content.removeAllViews();
		// Item layout
		View convertView = LayoutInflater.from(this).inflate(
				R.layout.bottle_list_avatar_item, null);
		// author img
		RemoteImageView mAuthorView = (RemoteImageView) convertView
				.findViewById(R.id.iv_author_photo);
		// bottle img
		ImageView mBottleType = (ImageView) convertView
				.findViewById(R.id.iv_bottle_type);
		// content layout
		LinearLayout contentLayout = (LinearLayout) convertView
				.findViewById(R.id.feed_post_body);

		View view = LayoutInflater.from(this).inflate(
				R.layout.bottle_list_detail_item, null);

		TextView mNickname = (TextView) view.findViewById(R.id.tv_nickname);
		TextView mLocation = (TextView) view.findViewById(R.id.tv_location);

		TextView mTag = (TextView) view.findViewById(R.id.tv_tag);
		TextView mCopyTips = (TextView) view.findViewById(R.id.tv_copy_info);
		TextView mood = (TextView) view.findViewById(R.id.tv_mood);

		RelativeLayout mBottleContent = (RelativeLayout) view
				.findViewById(R.id.rl_bottle_content);
		TextView mMessage = (TextView) view.findViewById(R.id.tv_doing);
		// photo
		LinearLayout mPhotoWrapper = (LinearLayout) view.findViewById(R.id.rl_bottle_content_photo);
		ImageView mPhotoView = (ImageView) view.findViewById(R.id.photo);

		Button bt_drawing = (Button)view.findViewById(R.id.bt_drawing); 
		Button bt_allow_draw = (Button)view.findViewById(R.id.bt_allow_draw);
		
		LinearLayout mLockedPhotoLayout = (LinearLayout) view
				.findViewById(R.id.ll_bottle_photo_locked);
		ImageView mLockedPhoto = (ImageView) view
				.findViewById(R.id.iv_locked_photo);
		Button mLockedPhotoTip = (Button) view
				.findViewById(R.id.bt_locked_photo_tips);

		// 喜欢popup
		RelativeLayout mLikeLayout = (RelativeLayout) view
				.findViewById(R.id.comment_button_like);

		ImageView mLikeIcon = (ImageView) view
				.findViewById(R.id.comment_button_like_icon);
		TextView mLikeText = (TextView) view
				.findViewById(R.id.comment_button_like_text);

		// 瓶子没打开的区域
		LinearLayout mUnopened_content = (LinearLayout) view
				.findViewById(R.id.ll_bottle_unopened_content);
		TextView mOpen_tips = (TextView) view
				.findViewById(R.id.tv_bottle_open_tips);
		Button mOpen = (Button) view.findViewById(R.id.bt_bottle_open);
		Button mDrop = (Button) view.findViewById(R.id.bt_bottle_drop);

		RelativeLayout mFeedComment = (RelativeLayout) view
				.findViewById(R.id.feed_comments);
		Button mComment = (Button) view.findViewById(R.id.bt_bottle_comment);

		Button mCopy = (Button) view.findViewById(R.id.bt_bottle_copy);
		Button mForward = (Button) view.findViewById(R.id.bt_bottle_forward);

		CustomGridView mLikeGrid = (CustomGridView) view
				.findViewById(R.id.ll_comment_like_grid);
		View line_grid = (View) view.findViewById(R.id.line_like_grid);
		View line_bt_comment = (View) view.findViewById(R.id.line_bt_comment);
		RelativeLayout mfeed_item_comment_more = (RelativeLayout) view
				.findViewById(R.id.feed_comments_more);
		TextView comments_ellipsis_text = (TextView) view
				.findViewById(R.id.comments_ellipsis_text);
		LinearLayout mfeed_comment_layout = (LinearLayout) view
				.findViewById(R.id.ll_feed_comment_layout);
		LinearLayout mOp_layout = (LinearLayout) view
				.findViewById(R.id.ll_botle_op);
		LinearLayout mOp_location = (LinearLayout) view
				.findViewById(R.id.ll_botle_op_location);
		RemoteImageView mOpAvatar = (RemoteImageView)view.findViewById(R.id.bt_opavatar);
		TextView mFeedContent = (TextView) view
				.findViewById(R.id.tv_feed_content);
		TextView mOplocation = (TextView) view.findViewById(R.id.tv_oplocation);
		TextView mOpDistance = (TextView) view.findViewById(R.id.tv_distance);
		contentLayout.addView(view);

		try {
			mAuthorView.setDefaultImage(R.drawable.avatar_default_big);
			mAuthorView.setImageUrl(message.getBt_avatar());
			BottleTypeTable btt = new BottleTypeTable();
			entry = btt.getBottleType(message.getBttypeid());
			btConfigLoader.DisplayImage(entry.getBttype_sjdicon(), mBottleType, R.drawable.bottle_type_1);
		} catch (Exception e) {
			e.printStackTrace();
			mAuthorView.setImageResource(R.drawable.avatar_default_big);
		}

		mAuthorView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int ouid = message.getBt_uid();
				Intent spaceIntent = new Intent(BottleSingleActivity.this, UserSpaceActivity.class);
				spaceIntent.putExtra("ouid", ouid);
				startActivity(spaceIntent);
			}
		});

		mBottleType.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				doSendSingleBtPri(message.getBttypeid(), message.getBtid());
			}
		});

		String nickName = (message.getBt_nickname() != null && message
				.getBt_nickname().length() > 0) ? ("<font color='#3F99D8'>"
				+ message.getBt_nickname() + "</font>") : "";
		String feed = (message.getBt_feed() != null && message.getBt_feed()
				.length() > 0) ? ("<font color='#000000'>"
				+ message.getBt_feed() + "</font>") : "";
			
		mNickname.setText(Html.fromHtml(nickName + feed));

		if (!TextUtils.isEmpty(message.getBt_location()) && message.getBt_open_drop_show() != 1) {
			mLocation.setVisibility(View.VISIBLE);
			String time = (!TextUtils.isEmpty(message.getBt_time())) ? ("<font color='#666666'>"+
							"#"+message.getBt_time() + "</font>") : "";		
			mLocation.setText(Html.fromHtml(time+message.getBt_location()));
			if (message.getBt_showaddress() == 1) {
				mLocation.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class);
						bottleDetailIntent.putExtra("btid", message.getBtid());
						bottleDetailIntent.putExtra("type", 2);// 1，LikeList2,location
						startActivity(bottleDetailIntent);
					}
				});
			}
		} else {
			mLocation.setVisibility(View.GONE);
		}

		if (!TextUtils.isEmpty(message.getBt_tag())) {
			mTag.setVisibility(View.VISIBLE);
			String locationTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_location_tips") + "</font>";
			mTag.setText(Html.fromHtml(locationTips + TextUtil.htmlEncode(message.getBt_tag())));
			
		} else {
			mTag.setVisibility(View.GONE);
		}

		if (!TextUtils.isEmpty(message.getBt_copy_info())) {
			mCopyTips.setVisibility(View.VISIBLE);
			String commentTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_forward_tips") + "</font>";
			mCopyTips.setText(Html.fromHtml(commentTips + message.getBt_copy_info()));
		} else {
			mCopyTips.setVisibility(View.GONE);
		}

		if (!TextUtils.isEmpty(message.getBt_doing())) {
			mood.setVisibility(View.VISIBLE);
			String moodTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_mood_tips") + "</font>";
			mood.setText(Html.fromHtml(moodTips + TextUtil.htmlEncode(message.getBt_doing())));
		} else {
			mood.setVisibility(View.GONE);
		}

		if (!TextUtils.isEmpty(message.getBt_content())) {
			String messageTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_copy_tips") + "</font>";
			mMessage.setVisibility(View.VISIBLE);
			mMessage.setText(Html.fromHtml(messageTips + TextUtil.htmlEncode(message.getBt_content())));
		} else {
			mMessage.setVisibility(View.GONE);
		}
		
		if (!TextUtils.isEmpty(message.getBt_opfeed())) {
			mOp_layout.setVisibility(View.VISIBLE);
			if (message.getBt_open_drop_show() != 1) {
				mOp_layout
						.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class);
								bottleDetailIntent.putExtra("btid", message.getBtid());
								bottleDetailIntent.putExtra("type", 2);// 1，LikeList2,location
								startActivity(bottleDetailIntent);
							}
						});
			}

			
			try {
				mOpAvatar.setDefaultImage(R.drawable.avatar_default_small);
				mOpAvatar.setImageUrl(message.getBt_opavatar());
				mOpAvatar.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								Intent spaceIntent = new Intent(BottleSingleActivity.this, UserSpaceActivity.class);
								spaceIntent.putExtra("ouid", message.getBt_opuid());
								startActivity(spaceIntent);
							}
						});
			} catch (Exception e) {
				e.printStackTrace();
				mOpAvatar.setImageResource(R.drawable.avatar_default_small);
			}
			
			String onickName = (!TextUtils.isEmpty(message.getBt_opnickname())) ? ("<font color='#3F99D8'>"
					+ message.getBt_opnickname() + "</font>") : "";
			String otime = (!TextUtils.isEmpty(message.getBt_optime())) ? ( "#" + message.getBt_optime()) : "";
					
			mFeedContent.setText(Html.fromHtml(onickName + TextUtil.htmlEncode(message.getBt_opfeed())));
			if (!TextUtils.isEmpty(message.getBt_oplocation())) {
				mOp_location.setVisibility(View.VISIBLE);
				mOplocation.setText(otime + message.getBt_oplocation());
				mOpDistance.setText(TextUtil.R("bottle_txt_comment_distance")+" "+message.getBt_opdistance());
			} else {
				mOp_location.setVisibility(View.GONE);
			}

		} else {
			mOp_layout.setVisibility(View.GONE);
		}
		

		if (message.getBt_open_drop_show() == 1) {
			mood.setVisibility(View.GONE);
			mMessage.setVisibility(View.GONE);
			mLikeLayout.setVisibility(View.GONE);
			mBottleContent.setVisibility(View.GONE);
			mUnopened_content.setVisibility(View.VISIBLE);
			mOpen_tips.setText(TextUtil.R("bottle_txt_open_tips") + " " + message.getBt_nickname());

			mOpen.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					doOpenBottle(message.getBtid());
				}
			});
			mDrop.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					doDropBottle(message.getBtid());
				}
			});

		} else {
			if (message.getBt_showaddress() == 1) {
				mTag.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class);
						bottleDetailIntent.putExtra("btid", message.getBtid());
						bottleDetailIntent.putExtra("type", 2);// 1，LikeList2,location
						startActivity(bottleDetailIntent);
					}
				});				
			}
			mood.setVisibility(View.VISIBLE);
			mMessage.setVisibility(View.VISIBLE);
			mLikeLayout.setVisibility(View.VISIBLE);
			mUnopened_content.setVisibility(View.GONE);
			mBottleContent.setVisibility(View.VISIBLE);
			if (!TextUtils.isEmpty(message.getBt_smallpic())) {

				if (message.getBt_pic_locked() == 0) {
					mPhotoWrapper.setVisibility(View.VISIBLE);
					mPhotoView.setVisibility(View.VISIBLE);
					mLockedPhotoLayout.setVisibility(View.GONE);
					try {
						imageLoader.DisplayImage(message.getBt_smallpic(), mPhotoView, R.drawable.album_nophoto);

					} catch (Exception e) {
						e.printStackTrace();
						mPhotoView.setImageResource(R.drawable.album_nophoto);
					}

					mPhotoView.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									byte[] tempBytes = null;
									try {
										String filename = ServiceUtils.convertUrlToFileName(message.getBt_smallpic());
										tempBytes = ServiceUtils.readStream(new FileInputStream(new File(
												android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename)));
									} catch (Exception e) {
										e.printStackTrace();
									}
									Intent bigPicIntent = new Intent(BottleSingleActivity.this, PhotoDetailActivity.class);
									bigPicIntent.putExtra("pic_big", message.getBt_bigpic());
									bigPicIntent.putExtra("thumbnail", tempBytes);
									startActivity(bigPicIntent);
								}
							});
					
					if (message.getBt_allow_tuya() == 1) {
						bt_drawing.setVisibility(View.VISIBLE);
						bt_drawing.setOnClickListener(new View.OnClickListener() {
							
							@Override
							public void onClick(View v) {
								int btId = message.getBtid();
								
								byte[] tempBytes = null;
								try {
									String filename = ServiceUtils.convertUrlToFileName(message.getBt_smallpic());
									tempBytes = ServiceUtils.readStream(new FileInputStream(new File(
											android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename)));
								} catch (Exception e) {
									e.printStackTrace();
								}
								
								Intent bigPicIntent = new Intent(BottleSingleActivity.this, PhotoDetailActivity.class);
								bigPicIntent.putExtra("pic_big", message.getBt_bigpic());
								bigPicIntent.putExtra("thumbnail", tempBytes);
								bigPicIntent.putExtra("paintType", AppContext.PAINT_BT);
								bigPicIntent.putExtra("btid", message.getBtid());
								bigPicIntent.putExtra("return_type",BottleSingleActivity.class.getSimpleName());
								bigPicIntent.putExtra("isToDraw", true);
								startActivity(bigPicIntent);			
								
							}
						});
					}else {
						bt_drawing.setVisibility(View.GONE);
					}
					
					if (message.getBt_enable_tuya()== 0) {
						bt_allow_draw.setVisibility(View.GONE);
					}else {
						bt_allow_draw.setVisibility(View.VISIBLE);
						if (message.getBt_enable_tuya()== 1) {
							bt_allow_draw.setBackgroundResource(R.drawable.btn_red_try);
							bt_allow_draw.setText(TextUtil.R("bottle_txt_allow_draw"));
							bt_allow_draw.setOnClickListener(new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									doPicPaint(message.getBtid(), 1);
								}
							});
						}else {
							bt_allow_draw.setBackgroundResource(R.drawable.btn_gray_try);
							bt_allow_draw.setText(TextUtil.R("bottle_txt_not_allow_draw"));
							bt_allow_draw.setOnClickListener(new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									doPicPaint(message.getBtid(), 0);
								}
							});
						}
					}
				
				} else {
					mLockedPhotoLayout.setVisibility(View.VISIBLE);
					mPhotoWrapper.setVisibility(View.GONE);
					mPhotoView.setVisibility(View.GONE);

					mLockedPhotoTip
							.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									Intent unLockPhotoIntent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class);
									Bundle unLockBundle = new Bundle();
									unLockBundle.putString("from_type", AppContext.REPLY_BT);
									unLockBundle.putString("return_type", BottleSingleActivity.class.getSimpleName());
									unLockBundle.putInt("bttype_id", message.getBtid());
									unLockPhotoIntent.putExtras(unLockBundle);
									startActivityForResult(unLockPhotoIntent, 0);
								}
							});
				}
			} else {
				mPhotoWrapper.setVisibility(View.GONE);
				mPhotoView.setVisibility(View.GONE);
				mLockedPhotoLayout.setVisibility(View.GONE);
			}

			if (null != message.getBtlikes_list()) {
				mLikeLayout.setVisibility(View.VISIBLE);

				if (message.getBt_liked() == 0) {
					mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.gray));
					mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill));
					mLikeIcon.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.like_gray2));
					// .setBackgroundResource(R.drawable.like_gray2);
				} else if (message.getBt_liked() == 1) {
					mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.gray));
					mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill));
					mLikeIcon.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.like_red2));
					// .setBackgroundResource(R.drawable.like_red2);
				} else if (message.getBt_liked() == 2) {
					mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.gray));
					mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill));
					mLikeIcon.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.like_black2));
					// .setBackgroundResource(R.drawable.like_black2);
				}

				if (message.getBt_like_enable() == 1) {
					mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.gray));
					mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill));
					mLikeLayout
							.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									showInfoPopupWindow(v, message.getBtid());
								}
							});
				} else {
					mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.white));
					mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill_dark));
				}
				
				if (message.getBtlikes_count() == 0) {
					mLikeText.setVisibility(View.GONE);
				} else {
					mLikeText.setVisibility(View.VISIBLE);
					mLikeText.setText(message.getBtlikes_count() + "");
				}
			} else {
				mLikeLayout.setVisibility(View.GONE);
			}

			mComment.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent commentIntent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class);
					Bundle commentBundle = new Bundle();
					commentBundle.putString("from_type", AppContext.REPLY_BT);
					commentBundle.putString("return_type", BottleSingleActivity.class.getSimpleName());
					commentBundle.putInt("bttype_id", message.getBtid());
					commentIntent.putExtras(commentBundle);
					startActivityForResult(commentIntent, 0);
				}
			});

			if (message.getBt_copy_enable() == 1) {
				mCopy.setVisibility(View.VISIBLE);
				mCopy.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent copyIntent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class);
						Bundle copyBundle = new Bundle();
						copyBundle.putString("from_type", AppContext.COPYMANUAL_BT);
						copyBundle.putInt("bttype_id", message.getBtid());
						copyBundle.putString("return_type", BottleSingleActivity.class.getSimpleName());
						copyIntent.putExtras(copyBundle);
						startActivityForResult(copyIntent, 0);
					}
				});
			} else {
				mCopy.setVisibility(View.INVISIBLE);
			}

			if (message.getBt_allow_spread() == 1) {
				mForward.setVisibility(View.VISIBLE);
				mForward.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						final Context dialogContext = new ContextThemeWrapper(BottleSingleActivity.this,
								android.R.style.Theme_Light);
						int btId = message.getBtid();
						String[] choices = new String[2];
						choices[0] = BottleSingleActivity.this.getString(R.string.bottle_txt_forward_to_friend);
						choices[1] = BottleSingleActivity.this.getString(R.string.bottle_txt_forward_to_platform);
						final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
								android.R.layout.simple_list_item_1, choices);

						final AlertDialog.Builder builder = new AlertDialog.Builder(
								dialogContext);
						builder.setTitle(R.string.system_info);
						builder.setSingleChoiceItems(adapter, -1,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int which) {
										dialog.dismiss();
										if (which == 0) {
											
											Intent forwardIntent = new Intent(BottleSingleActivity.this, ChooseFriendActivity.class);
											Bundle forwardBundle = new Bundle();
											forwardBundle.putInt("choose_friend_type", AppContext.CHOOSE_FRIEND_FORWARD_BOTTLE_TYPE);
											forwardBundle.putInt("bttype_id", message.getBtid());
											forwardBundle.putString("return_type", BottleSingleActivity.class.getSimpleName());
											forwardIntent.putExtras(forwardBundle);
											startActivity(forwardIntent);	
											
											
										} else {
											Intent forwardIntent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class);
											Bundle forwardBundle = new Bundle();
											forwardBundle.putString("from_type", AppContext.TRANSMIT_BT);
											forwardBundle.putString("return_type", BottleSingleActivity.class.getSimpleName());
											forwardBundle.putInt("bttype_id", message.getBtid());
											forwardIntent.putExtras(forwardBundle);
											startActivityForResult(forwardIntent, 0);									
											}
									}
								});
						builder.create().show();
						
					}
				});
			} else {
				mForward.setVisibility(View.INVISIBLE);
			}
			
			if (null != message.getBtlikes_list()
					&& message.getBtlikes_list().size() > 0) {
				mLikeGrid.setVisibility(View.VISIBLE);
				line_grid.setVisibility(View.VISIBLE);
				final GridLikeAdapter gridAdapter = new GridLikeAdapter(
						BottleSingleActivity.this, message.getBtlikes_list(), mLikeGrid);
				mLikeGrid.setAdapter(gridAdapter);
				mLikeGrid
						.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
								BottleLikeEntry btLike = (BottleLikeEntry) gridAdapter.getItem(position);
								Intent spaceIntent = new Intent(BottleSingleActivity.this, UserSpaceActivity.class);
								spaceIntent.putExtra("ouid", btLike.getLike_uid());
								startActivity(spaceIntent);
							}
						});
			} else {
				mLikeGrid.setVisibility(View.GONE);
				line_grid.setVisibility(View.GONE);
			}

			if (message.getBtfeeds_count() > 0) {
				line_bt_comment.setVisibility(View.VISIBLE);
				mfeed_item_comment_more.setVisibility(View.VISIBLE);

				mfeed_item_comment_more
						.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class);
								bottleDetailIntent.putExtra("btid", message.getBtid());
								bottleDetailIntent.putExtra("type", 1);// 2,location
								startActivity(bottleDetailIntent);
							}
						});

				comments_ellipsis_text.setText(message
						.getBtfeeds_count()+"  " + TextUtil.R("bottle_txt_comment_more"));
			} else {
				mfeed_item_comment_more.setVisibility(View.GONE);
				line_bt_comment.setVisibility(View.INVISIBLE);
			}

			if (message.getBtfeeds_count() > 0) {
				mfeed_comment_layout.setVisibility(View.VISIBLE);
				mfeed_comment_layout.removeAllViews();

				for (int i = 0; i < message.getBtfeeds_list().size(); i++) {
					final BottleFeedEntry btFeedEntry = message.getBtfeeds_list().get(i);
					View mCommentView = LayoutInflater.from(BottleSingleActivity.this).inflate(
							R.layout.feed_comments_item, null);
					if (i == (message.getBtfeeds_list().size()-1)) {
						View feed_avatar = (View) mCommentView
								.findViewById(R.id.line_bttimeline_feed);
						feed_avatar.setVisibility(View.INVISIBLE);
					}
					mCommentView.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class);
							bottleDetailIntent.putExtra("btid", message.getBtid());
							bottleDetailIntent.putExtra("type", 1);// 1，LikeList2,location
							startActivity(bottleDetailIntent);
						}
					});
					RemoteImageView feed_avatar = (RemoteImageView) mCommentView
							.findViewById(R.id.comment_profile_photo);
					if (!TextUtils.isEmpty(btFeedEntry.getFeed_avatar())) {

						try {
							feed_avatar.setDefaultImage(R.drawable.avatar_default_small);
							feed_avatar.setImageUrl(btFeedEntry.getFeed_avatar());
							feed_avatar
									.setOnClickListener(new View.OnClickListener() {

										@Override
										public void onClick(View v) {
											Intent spaceIntent = new Intent(BottleSingleActivity.this, UserSpaceActivity.class);
											spaceIntent.putExtra("ouid", btFeedEntry.getFeed_uid());
											startActivity(spaceIntent);
										}
									});
						} catch (Exception e) {
							e.printStackTrace();
							feed_avatar.setImageResource(R.drawable.avatar_default_small);
						}
					}
//					ImageView comment_link = (ImageView) mCommentView
//							.findViewById(R.id.iv_feed_comment_white);
//					if (btFeedEntry.getFeed_type() == 0) {
//						comment_link.setVisibility(View.VISIBLE);
//					} else {
//						comment_link.setVisibility(View.GONE);
//					}
					TextView comment_nickname = (TextView) mCommentView
							.findViewById(R.id.tv_feed_comment_nickname);
					String feed_name = null;
					if ((!TextUtils.isEmpty(btFeedEntry.getFeed_nickname()))|| (!TextUtils.isEmpty(btFeedEntry.getFeed_content()))) {
						if (btFeedEntry.getFeed_uid() != AppContext.getInstance()
								.getLogin_uid()) {
							feed_name = "<font color='#DA4A37'>"
									+ btFeedEntry.getFeed_nickname()
									+ "</font>";
						} else {
							feed_name = "<font color='#3F99D8'>"
									+ btFeedEntry.getFeed_nickname()
									+ "</font>";
						}
						
						String feed_content = btFeedEntry.getFeed_isnew()==1?("<font color='#DA4A37'>"
								+ TextUtil.htmlEncode(btFeedEntry.getFeed_content())
								+ "</font>"):TextUtil.htmlEncode(btFeedEntry.getFeed_content());
						
						try {
							comment_nickname.setText(Html.fromHtml(feed_name
									+ " " + feed_content));
						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					TextView comment_time = (TextView) mCommentView
							.findViewById(R.id.tv_feed_comment_time);
					if ((!TextUtils.isEmpty(btFeedEntry.getFeed_time())) || (!TextUtils.isEmpty(btFeedEntry.getFeed_location()))) {
						String timeComent = (!TextUtils.isEmpty(btFeedEntry.getFeed_time())) ? ("#" + btFeedEntry.getFeed_time()): "";
						String location = (!TextUtils.isEmpty(btFeedEntry.getFeed_location().trim())) ? ("@" + btFeedEntry.getFeed_location()): "";
						comment_time.setText(timeComent+" "+location);
						if (!TextUtils.isEmpty(location)) {
							comment_time.setOnClickListener(new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									final Context dialogContext = new ContextThemeWrapper(BottleSingleActivity.this,
											android.R.style.Theme_Light);
									String[] choices = new String[1];
									choices[0] = BottleSingleActivity.this.getString(R.string.bottle_txt_check_location);

									final ListAdapter adapter = new ArrayAdapter<String>(
											dialogContext,
											android.R.layout.simple_list_item_1,
											choices);

									final AlertDialog.Builder builder = new AlertDialog.Builder(
											dialogContext);
									builder.setTitle(R.string.system_info);
									builder.setSingleChoiceItems(
											adapter,
											-1,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();
													if (which == 0) {
														Intent intent = new Intent(BottleSingleActivity.this,MapViewActivity.class);
														intent.putExtra(
																"longitude",btFeedEntry.getFeed_lng());
														intent.putExtra(
																"latidute",btFeedEntry.getFeed_lat());
														intent.putExtra(
																"location",btFeedEntry.getFeed_location());
														startActivity(intent);
													}
												}
											});
									builder.create().show();
								}
							});	
						}
					}
					RelativeLayout rl_bottle_comment_photo = (RelativeLayout)mCommentView.findViewById(R.id.rl_bottle_comment_photo);
					if (!TextUtils.isEmpty(btFeedEntry.getFeed_commentpic())) {
						rl_bottle_comment_photo.setVisibility(View.VISIBLE);
						ImageView feed_commentpic = (ImageView)mCommentView.findViewById(R.id.feed_comment_pic);
						try {
							imageLoader.DisplayImage(btFeedEntry.getFeed_commentpic(),feed_commentpic,
									R.drawable.album_nophoto);
							feed_commentpic
									.setOnClickListener(new View.OnClickListener() {

										@Override
										public void onClick(View v) {

											if (!TextUtils.isEmpty(btFeedEntry
													.getFeed_commentpic_tuya())) {
												showCommentPicFeedDialog(btFeedEntry);
											} else {
												byte[] tempBytes = null;
												try {
													String filename = ServiceUtils
															.convertUrlToFileName(btFeedEntry
																	.getFeed_commentpic());
													tempBytes = ServiceUtils
															.readStream(new FileInputStream(
																	new File(
																			android.os.Environment
																					.getExternalStorageDirectory()
																					+ "/"
																					+ AppContext.BottleTimelineIcon
																					+ "/"
																					+ filename)));
												} catch (Exception e) {
													e.printStackTrace();
												}
												Intent bigPicIntent = new Intent(BottleSingleActivity.this,
														PhotoDetailActivity.class);
												bigPicIntent.putExtra("pic_big",btFeedEntry.getFeed_commentpic_big());
												bigPicIntent.putExtra("thumbnail",
														tempBytes);
												startActivity(bigPicIntent);

											}
										
										}
									});
						} catch (Exception e) {
							e.printStackTrace();
							feed_commentpic.setImageResource(R.drawable.album_nophoto);
						}
					}else {
						rl_bottle_comment_photo.setVisibility(View.GONE);
					}
					
					TextView tv_feed_replycomment = (TextView)mCommentView.findViewById(R.id.tv_feed_replycomment);
					if (!TextUtils.isEmpty(btFeedEntry.getFeed_replycomment())) {
						tv_feed_replycomment.setVisibility(View.VISIBLE);
						tv_feed_replycomment.setText(btFeedEntry.getFeed_replycomment());
					} else {
						tv_feed_replycomment.setVisibility(View.GONE);
					}
					
					mfeed_comment_layout.addView(mCommentView);
				}
			} else {
				mfeed_comment_layout.setVisibility(View.GONE);
			}
		}
		ll_content.addView(convertView);
	}
	public void doDropBottle(int btId) {
		this.btId = btId;
		UICore.eventTask(this, this, EXEU_DROP_BOTTLE_OPERATION, "", null);
	}
	public void doSendSingleBtPri(int btTypeId, int btId) {
		this.btId = btId;
		this.btTypeId = btTypeId;
		UICore.eventTask(this, this, EXEU_GET_BOTTLE_PRIV_OPERATION, "", null);
	}

	private void initLikePopup() {
		LayoutInflater mLayoutInflater = LayoutInflater.from(this);
		View mLikeView = mLayoutInflater.inflate(R.layout.pop_bottle_like,
				null);
		ImageView iv_unlike = (ImageView) mLikeView
				.findViewById(R.id.iv_unlike);
		ImageView iv_like = (ImageView) mLikeView.findViewById(R.id.iv_like);
		iv_unlike.setOnClickListener(this);
		iv_like.setOnClickListener(this);
		mLikePopview = new CustomPopupWindow(mLikeView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mLikePopview.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.ic_launcher));
		mLikePopview.setOutsideTouchable(true);
		mLikePopview.update();
		mLikePopview.setTouchable(true);
		mLikePopview.setFocusable(true);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_unlike:// 不喜欢
			mLikePopview.dismiss();
			UICore.eventTask(this, this, EXEU_UNLIKE_OPERATION, "", null);
			break;
		case R.id.iv_like:// 喜欢
			mLikePopview.dismiss();
			UICore.eventTask(this, this, EXEU_LIKE_OPERATION, "", null);
			break;
		case R.id.topbar_back:
			finish();
			break;
		case R.id.rl_button_like:
			mLikePopview.showAsDropDown(v, 50, -40);
			break;
		case R.id.bt_bottle_comment:
			Intent commentIntent = new Intent(this, ExpandEditActivity.class);
			Bundle commentBundle = new Bundle();
			commentBundle.putString("from_type", AppContext.REPLY_BT);
			commentBundle.putInt("bttype_id", btId);
			commentIntent.putExtras(commentBundle);
			startActivityForResult(commentIntent, 0);
			break;
		case R.id.bt_bottle_copy:
			Intent copyIntent = new Intent(this, ExpandEditActivity.class);
			Bundle copyBundle = new Bundle();
			copyBundle.putString("from_type", AppContext.COPYMANUAL_BT);
			copyBundle.putInt("bttype_id", btId);
			copyIntent.putExtras(copyBundle);
			startActivityForResult(copyIntent, 0);
			break;
		case R.id.bt_bottle_forward:
			Intent forwardIntent = new Intent(this, ExpandEditActivity.class);
			Bundle forwardBundle = new Bundle();
			forwardBundle.putString("from_type", AppContext.TRANSMIT_BT);
			forwardBundle.putInt("bttype_id", btId);
			forwardIntent.putExtras(forwardBundle);
			startActivityForResult(forwardIntent, 0);
			break;
//		case R.id.notice_message_count:		
//			doMessageAction();
//			break;
		default:
			break;
		}
	}
	public void doMessageAction() {
		
		final Context dialogContext = new ContextThemeWrapper(this,
				android.R.style.Theme_Light);
		String[] choices = new String[2];
		choices[0] = getString(R.string.bottle_txt_notice_list);
		choices[1] = getString(R.string.bottle_txt_message_list);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (which == 0) {
							Intent intent = new Intent(BottleSingleActivity.this, NoticeListActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(BottleSingleActivity.this, MessageListActivity.class);
							startActivity(intent);
						}
					}
				});
		builder.create().show();
	}
	/**
	 * 喜欢瓶子的操作
	 * 
	 * @param btId
	 *            瓶子ID
	 * @param likeType
	 *            喜欢or不喜欢 <---> 1 or 2
	 */
	private void likeOperation(int btId, int likeType) {
		StringBuffer url = new StringBuffer(UrlConfig.likeop_bt);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		url.append("&liketype=" + likeType);
		ServiceUtils.dout("likeOperation url:" + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("likeOperation result:" + results);
			if (null != results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int success = resultObj.getInt("success");
				String errmsg = resultObj.getString("errmsg");
				String successmsg = resultObj.getString("successmsg");
				Message message = null;
				if (success == 1) {

					switch (likeType) {
					case 1:
						message = handler.obtainMessage(EXEU_LIKE_OPERATION,
								successmsg);
						handler.sendMessage(message);
						break;
					case 2:
						message = handler.obtainMessage(EXEU_UNLIKE_OPERATION,
								successmsg);
						handler.sendMessage(message);
						break;
					default:
						break;
					}
				} else {
					message = handler.obtainMessage(EXEU_LIKE_OPERATION_FAILED,
							errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPicPaint(int btid,int optype){
		this.btId = btid;
		UICore.eventTask(this, this, EXEU_SET_BTPIC_PAINT, "", optype);
	}
	
	private void getBottleInfo(int btId) {
		StringBuffer url = new StringBuffer(UrlConfig.get_btinfo);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		ServiceUtils.dout("getBottleInfo url: " + url.toString());
		try {
			String results = HttpUtils.doGet(url.toString());

			if (results == null) {
				return;
			}
			ServiceUtils.dout("getBottleInfo results:" + results.toString());
			Gson gson = new Gson();
			BottleInfo bottleInfo = gson.fromJson(results, BottleInfo.class);

			if (bottleInfo.getResults().getAuthok() == 1) {

//				bottleInfoEntry = bottleInfo.getBtinfo();
				// Message message =
				// handler.obtainMessage(EXEU_GET_BOTTLE_INFO,bottleInfoEntry);
				// handler.sendMessage(message);
			} else {
				// Message message = handler.obtainMessage(EXEU_GET_DATA_ERROR,
				// bottleInfo.getResults().getErrmsg());
				// handler.sendMessage(message);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	protected void onResume() {
		super.onResume();
		if (AppContext.getInstance().isFromBottleSingle()) {
			AppContext.getInstance().setFromBottleSingle(false);
			page = 1;
			UICore.eventTask(this, BottleSingleActivity.this,
					EXEU_GET_TIMELINE, "", null);
		}
		
	};
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent intent) {
		super.onActivityResult(arg0, arg1, intent);

		if (null != intent) {
			if (intent.getBooleanExtra("need_refresh", false)) {
				page = 1;
				UICore.eventTask(this, BottleSingleActivity.this,
						EXEU_GET_TIMELINE, "", null);
			}
		}
	}


	private void showCommentPicFeedDialog(final BottleFeedEntry  message) {
		String[] choices = new String[]{TextUtil.R("bottle_txt_feed_comment_pic"),TextUtil.R("bottle_txt_feed_comment_tuya")};
		final Context dialogContext = new ContextThemeWrapper(BottleSingleActivity.this, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (which == 0) {

							byte[] tempBytes = null;
							try {
								String filename = ServiceUtils.convertUrlToFileName(message.getFeed_commentpic());
								tempBytes = ServiceUtils.readStream(new FileInputStream(new File(
										android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename)));
							} catch (Exception e) {
								e.printStackTrace();
							}
							Intent bigPicIntent = new Intent(BottleSingleActivity.this, PhotoDetailActivity.class);
							bigPicIntent.putExtra("pic_big", message.getFeed_commentpic_big());
							bigPicIntent.putExtra("thumbnail", tempBytes);
							startActivity(bigPicIntent);
							
						} else {
							Intent bigPicIntent = new Intent(BottleSingleActivity.this, PhotoDetailActivity.class);
							bigPicIntent.putExtra("pic_big", message.getFeed_commentpic_tuya());
							startActivity(bigPicIntent);
						}
					}
				});
		builder.create().show();
	}
	
	
	public void doOpenBottle(int btId) {
		this.btId = btId;
		UICore.eventTask(this, this, EXEU_OPEN_BOTTLE_OPERATION, "", null);
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case EXEU_GET_TIMELINE:
			setViewVlaue(mBottleList.get(0));
			if (isRefresh) {
				rv.finishRefresh();
			}
			break;
		case EXEU_GET_TIMELINE_FAILED:
			onToast((String) msg.obj);
			break;
		case EXEU_OPEN_BOTTLE_FAILED:
			onToast((String) msg.obj);
			break;
		case EXEU_GET_DATA_FAILED:
			onToast(TextUtil.R("no_more_data"));
			break;
		case EXEU_OPEN_BOTTLE_SUCCESS:
			setViewVlaue(mBottleList.get(0));
			break;
		case EXEU_DROP_BOTTLE_SUCCESS:
			ll_content.removeAllViews();
			onToast((String) msg.obj);
			break;
		case EXEU_DROP_BOTTLE_FAILED:
			onToast((String) msg.obj);
			break;
		case EXEU_SEND_BOTTLE_PRIV_SUCCESS:
			final Bundle bundle = msg.getData();
			try {
				BottleTypeTable table = new BottleTypeTable();
				BottleTypeEntry bottleEntry = table.getBottleType(bundle.getInt("type"));
				int locationSelect = bottleEntry.getBttype_location_select();
				String[] choices = new String[2];
				if (locationSelect > 1) {
					choices[0] = getString(R.string.choose_location_here_throw);
					choices[1] = getString(R.string.choose_location_search_throw);
				} else {
					choices = new String[1];
					choices[0] = getString(R.string.choose_location_here_throw);
				}
				chooseAction(choices, locationSelect , bundle.getInt("type"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE:
			onToast((String) msg.obj);
			break;
		case EXEU_SEND_BOTTLE_PRIV_FAILED:
			onToast((String) msg.obj);
			break;
		case EXEU_LIKE_OPERATION_FAILED:
			onToast((String) msg.obj);
			break;
		case EXEU_LIKE_OPERATION:
			UICore.eventTask(this, BottleSingleActivity.this,
					EXEU_REFRESH_CONTENT, "", null);
			break;
		case EXEU_UNLIKE_OPERATION:
			UICore.eventTask(this, BottleSingleActivity.this,
					EXEU_REFRESH_CONTENT, "", null);
			break;
		case EXEU_GET_DATA_NOTHING:
			rv.mfooterViewText.setVisibility(View.INVISIBLE);
			onToast(TextUtil.R("no_more_data"));
			rv.finishRefresh();
			break;
		case throw_bottle_init_location:
			try {
				Object[] objs = (Object[]) msg.obj;
				int bottleid = Integer.parseInt(objs[0].toString());
				LocationEntry location = (LocationEntry) objs[1];
				Intent intent2 = new Intent(this, ThrowBottleSettingActivity.class);
				intent2.putExtra("bttype_id", bottleid);
				intent2.putExtra("bt_geo_lng", location.getLongitude());
				intent2.putExtra("bt_geo_lat", location.getLatitude());
				startActivity(intent2);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case EXEU_SET_BTPIC_PAINT:
			onToast((String) msg.obj);
			UICore.eventTask(this, BottleSingleActivity.this,
					EXEU_REFRESH_CONTENT, "", null);
			break;
		default:
			break;
		}
		return false;
	}
	public void showInfoPopupWindow(View achorView, int btId) {
		this.btId = btId;

		if (mLikePopview.isShowing()) {
			mLikePopview.dismiss();
		} else {
			// mLikePopview.showAtLocation(achorView, Gravity.RIGHT, 0, 0);
			mLikePopview.showAsDropDown(achorView, -150, -50);
		}
	}
	
	private void chooseAction(String[] choices, final int locationSelected, final int bottleId) {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (which == 0) {
							Intent intent2 = new Intent(BottleSingleActivity.this, ThrowBottleSettingActivity.class);
							intent2.putExtra("bttype_id", bottleId);
							intent2.putExtra("bt_geo_lng", AppContext.getInstance().getLongitude());
							intent2.putExtra("bt_geo_lat", AppContext.getInstance().getLatitude());
							startActivity(intent2);
						} else {
							Intent intent = new Intent(BottleSingleActivity.this, ChooseLocationTabsActivity.class);
							intent.putExtra("type", "throw");
							intent.putExtra("bottleId", bottleId);
							intent.putExtra("locationSelect", locationSelected);
							startActivity(intent);
						}
					}
				});
		builder.create().show();
	}
}
